package com.atguigu.day01;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class Flink02_Stream_BoundedWordCount {
    public static void main(String[] args) throws Exception {
        //1.获取 流 的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //将并行度设置为1 为了看起来方便
        env.setParallelism(1);

        //2.从文件读取数据
        DataStreamSource<String> streamSource = env.readTextFile("input/word.txt");

        //3.对读过来的数据 转为Tuple2元组
        SingleOutputStreamOperator<Tuple2<String, Integer>> wordToOneStream = streamSource.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            /**
             *
             * @param value 输入的数据
             * @param out 收集器 用来把数据发送至下游
             * @throws Exception
             */
            @Override
            public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
                String[] words = value.split(" ");
                for (String word : words) {
                    out.collect(Tuple2.of(word, 1));
                }
            }
        });

        //4.对相同的单词聚合
        KeyedStream<Tuple2<String, Integer>, Tuple> keyedStream = wordToOneStream.keyBy("f0");

        //5.累加
        SingleOutputStreamOperator<Tuple2<String, Integer>> result = keyedStream.sum("f1");

        result.print();

        //执行程序 每掉一个execute就会生成一个job
        env.execute();
    }
}
